import React, { useState, useEffect, useRef } from 'react'
import { Button, Switch, Table, Modal } from 'antd'
import {
  DeleteOutlined,
  UnorderedListOutlined,
  ExclamationCircleFilled
} from '@ant-design/icons';
import axios from 'axios';
import UserForm from '../../../components/user-manage/UserForm';

const { confirm } = Modal;


function UserList() {
  const [dataSource, setdataSource] = useState([]);
  const [isAndVisible, setisAndVisible] = useState(false)
  const [roleList, setroleList] = useState([])
  const [regionList, setregionList] = useState([])
  const [isUpdateVisible, setisUpdateVisible] = useState(false)
  const [isUpdateDisabled, setisUpdateDisabled] = useState(false)
  const [current, setcurrent] = useState(null)

  const addForm = useRef(null);//形成一个ref与组件UserForm直接形成联动和数据的传递
  const updateForm = useRef(null);

  const columns = [
    {
      title: "区域",
      dataIndex: "region",
      filters: [
        ...regionList.map(item => ({
          text: item.title,
          value: item.value
        })),
        {
          text: "全球",
          value: "全球"
        }
      ],
      render: (region) => {
        return <b>{region === "" ? "全球" : region}</b>
      },
      onFilter: (value, item) => {
        if (value === "全球") {
          return item.region === ""
        }
        return item.region === value
      },
    },
    {
      title: "角色名称",
      dataIndex: "role",
      render: (role) => {
        return role.roleName
      }
    },
    {
      title: "用户名",
      dataIndex: "username"
    },
    {
      title: "用户状态",
      dataIndex: "roleState",
      render: (roleState, item) => {
        return <Switch
          checked={roleState}
          disabled={item.default}
          onChange={() => handleChange(item)}
        ></Switch>
      }
    },
    {
      title: "操作",
      render: (item) => {
        return <div>
          <Button
            danger
            shape='circle'
            icon={<DeleteOutlined
              onClick={() => confirmMethod(item)}
            />}
            disabled={item.default}
          ></Button>

          <Button
            type='primary'
            shape='circle'
            icon={<UnorderedListOutlined />}
            style={{ margin: "0px 10px" }}
            onClick={() => {
              handleUpdate(item)
            }}
            disabled={item.default}
          ></Button>

        </div>
      }
    }
  ];

  const { roleId, username, region } = JSON.parse(localStorage.getItem("token"))

  useEffect(() => {
    const roleObj = {
      "1": "superadmin",
      "2": "admin",
      "3": "editor"
    }
    axios.get('/users?_expand=role').then((res) => {
      const list = res.data;
      // console.log(roleId);
      setdataSource(roleObj[roleId] === "superadmin" ? list : [
        ...list.filter(item => item.username === username),
        ...list.filter(item => item.region === region && roleObj[item.roleId] === "editor")
      ])
    })
  }, [roleId, username, region]);

  useEffect(() => {
    axios.get('/regions').then((res) => {
      const list = res.data
      setregionList(list)
    })
  }, []);
  useEffect(() => {
    axios.get('/roles').then((res) => {
      const list = res.data;
      setroleList(list)
    })
  }, []);



  // 给删除按钮绑定点击事件
  const confirmMethod = (item) => {
    confirm({
      title: '你确定要删除?',
      icon: <ExclamationCircleFilled />,
      onOk() {
        deleteMethod(item)
      }
    });
  }
  const deleteMethod = (item) => {
    // 当前页面同步操作 + 后端同步
    setdataSource(dataSource.filter(data => data.id !== item.id))
    axios.delete(`/users/${item.id}`)
  }

  const addFormOk = () => {
    addForm.current.validateFields().then((value) => {
      setisAndVisible(false);
      axios.post(`/users`, {
        ...value,
        "roleState": true,
        "default": false
      }).then((res) => {
        setdataSource([...dataSource, {
          ...res.data,
          role: roleList.filter(item => item.id === value.roleId)[0]
        }])
      })
      addForm.current.resetFields();
    }).catch((err) => {
      console.log(err);
    })
  }


  const handleChange = (item) => {
    item.roleState = !item.roleState;
    setdataSource([...dataSource]);
    axios.patch(`/users/${item.id}`, {
      roleState: item.roleState
    })
  }

  const handleUpdate = (item) => {
    // console.log(item.username);
    setisUpdateVisible(true);
    setTimeout(() => {
      if (item.roleId === 1) {
        setisUpdateDisabled(true)
      } else {
        setisUpdateDisabled(false)

      }
      updateForm.current.setFieldsValue(item);
    }, 100);
    setcurrent(item)
  }


  const updateFormOk = () => {
    updateForm.current.validateFields().then((value) => {
      setisUpdateVisible(false);
      setdataSource(dataSource.map(item => {
        if (item.id === current.id) {
          return {
            ...item,
            ...value,
            role: roleList.filter(data => data.id === value.roleId)[0]
          }
        }
        return item
      }))
      setisUpdateDisabled(!isUpdateDisabled)
      axios.patch(`/users/${current.id}`, value)
    }).catch((err) => {
      console.log(err);
    })
  }

  return (
    <div>
      <Button type='primary' onClick={() => {
        setisAndVisible(true);
      }}>添加用户</Button>
      <Table
        dataSource={dataSource}
        columns={columns}
        rowKey={item => item.id
        }
        pagination={{
          pageSize: 5
        }}
      >

      </Table>

      <Modal
        open={isAndVisible}
        title="添加用户"
        okText="确定"
        cancelText="取消"
        onCancel={() => {
          setisAndVisible(false)
        }}
        onOk={() => addFormOk()}
      >
        <UserForm ref={addForm} regionList={regionList} roleList={roleList}></UserForm>
      </Modal>

      <Modal
        open={isUpdateVisible}
        title="更新用户"
        okText="更新"
        cancelText="取消"
        onCancel={() => {
          setisUpdateVisible(false)
          setisUpdateDisabled(!isUpdateDisabled)
        }}
        onOk={() => updateFormOk()}
      >
        <UserForm 
        ref={updateForm} 
        isUpdateDisabled={isUpdateDisabled}
         regionList={regionList} 
         roleList={roleList}
         isUpdate={true}
         ></UserForm>
      </Modal>
    </div>
  )
}

export default UserList
